import { useEffect, useState } from 'react'
import { fetchDeleteNotice, fetchGetNotice, fetchSetNoticeRead } from '@/api/message'
import { FetchNotice, INotice } from '@/api/message/interface'
import { transNotices } from '@/api/message/translator'
import { useRequest } from 'ahooks'
import { fetchGetPlatformServiceUrl } from '@/api/global'
export const useNotices = () => {
	const [isLoading, setIsLoading] = useState(true)
	const [hasNew, setHasNew] = useState(false)
	const [noticeList, setNoticeList] = useState<INotice[]>([])
	const { run } = useRequest(fetchGetNotice, {
		manual: true,
		onSuccess: (data) => {
			setIsLoading(false)
			if (data && data.total > 0) {
				let list = data.data
				let noReadMoids = list.filter((i) => i.read_state === 0).map((j) => j.moid)
				fetchSetNoticeRead(noReadMoids)
				//将列表中所有消息置为已读
				list = list.map((item) => ({ ...item, read_state: 1 }))
				updateData(list)
			} else {
				setNoticeList([])
			}
		},
	})
	useEffect(() => {
		nextIntegralPointAfterLoadMessage()
	}, [])
	const setTimeoutToloadMessage = () => {
		/** 保证每次均在 0，15，30，45 整点分钟后 10s 获取消息数据 */
		let interval = 0,
			dateIntegralPoint = new Date(),
			date = new Date() //现在时刻
		dateIntegralPoint.setMinutes(date.getMinutes() + 15 - (date.getMinutes() % 15))
		dateIntegralPoint.setSeconds(10) //延迟10秒钟获取
		interval = dateIntegralPoint.getTime() - date.getTime()
		setTimeout(() => {
			nextIntegralPointAfterLoadMessage()
		}, interval)
	}
	const nextIntegralPointAfterLoadMessage = () => {
		fetchGetNotice().then((data) => {
			if (data && data.total > 0) {
				updateData(data.data)
			} else {
				setNoticeList([])
			}
		})
		setTimeoutToloadMessage() //开始下一次计时
	}
	useEffect(() => {
		let flag = false
		noticeList.forEach((notice) => {
			if (notice.read_state === 0) {
				flag = true
				return
			}
		})
		setHasNew(flag)
	}, [noticeList])
	const updateData = (list: FetchNotice[]) => {
		fetchGetPlatformServiceUrl().then((data) => {
			setNoticeList(transNotices(list, data))
		})
	}
	const clearNotification = (moid: string) => {
		fetchDeleteNotice([moid]).then((res) => {
			if (res) {
				setNoticeList(noticeList.filter((i) => i.moid !== moid))
			}
		})
	}
	const clearAllNotification = () => {
		let moids = noticeList.map((notice) => notice.moid)
		fetchDeleteNotice(moids).then((res) => {
			if (res) {
				setNoticeList([])
			}
		})
	}
	const openNoticePanel = () => {
		run()
	}
	const closeNoticePanel = () => {
		setIsLoading(true)
		setNoticeList([])
	}
	return {
		isLoading,
		hasNew,
		noticeList,
		openNoticePanel,
		closeNoticePanel,
		clearNotification,
		clearAllNotification,
	}
}
